//
//  B_ SweepViewController.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/8/19.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_SweepViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "B_SweepMainView.h"
#import "B_QrCodeViewController.h"

@interface B_SweepViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureSession * session;
@property (nonatomic, strong) AVCaptureDevice * captureDevice;

@property (nonatomic, strong) B_SweepMainView * sweepView;

@end

@implementation B_SweepViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"扫一扫"];
    [self setSweep];
    [self.view addSubview:self.sweepView];
    [_sweepView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(-getNavHeight());
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [self.sweepView startAmination];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (B_SweepMainView *)sweepView {
    if (!_sweepView) {
        WeakSelf(weSelf, self);
        _sweepView = [B_SweepMainView initB_SweepMainView];
        _sweepView.myQrCodeAction = ^{
            //TODO: 打开我的二维码
            B_QrCodeViewController * qrCode = [[B_QrCodeViewController alloc] init];
            [weSelf pushNextViewController:qrCode];
        };
    }
    return _sweepView;
}


- (AVCaptureSession *) session {
    if (!_session) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}
- (AVCaptureDevice *) captureDevice {
    if (!_captureDevice) {
        _captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];;
    }
    return _captureDevice;
}

- (void)setSweep {
    //创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:self.captureDevice error:nil];
    //判断输入流是否可用
    if (input) {
        //创建输出流
        AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
        //设置代理,在主线程里刷新,注意此时self需要签AVCaptureMetadataOutputObjectsDelegate协议
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        
        /// 设置扫描区域的大小
        CGSize size = self.view.bounds.size;
        CGRect cropRect = CGRectMake(SCREEN_WIDTH / 2. - 125, SCREEN_HEIGHT / 2. - getNavHeight() - 125, 250, 250);
        CGFloat p1 = size.height/size.width;
        CGFloat p2 = 1920./1080.;  //使用了1080p的图像输出
        if (p1 < p2) {
            CGFloat fixHeight = self.view.bounds.size.width * 1920. / 1080.;
            CGFloat fixPadding = (fixHeight - size.height)/2;
            output.rectOfInterest = CGRectMake((cropRect.origin.y + fixPadding)/fixHeight,
                                               cropRect.origin.x/size.width,
                                               cropRect.size.height/fixHeight,
                                               cropRect.size.width/size.width);
        } else {
            CGFloat fixWidth = self.view.bounds.size.height * 1080. / 1920.;
            CGFloat fixPadding = (fixWidth - size.width)/2;
            output.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,
                                               (cropRect.origin.x + fixPadding)/fixWidth,
                                               cropRect.size.height/size.height,
                                               cropRect.size.width/fixWidth);
        }
        //        [output setRectOfInterest:CGRectMake(SCREEN_HEIGHT / 2. - 125, SCREEN_WIDTH / 2. - 125, 250, 250)];
        //初始化连接对象
        //self.session //= [[AVCaptureSession alloc]init];
        //高质量采集率
        [self.session setSessionPreset:AVCaptureSessionPresetHigh];
        [self.session addInput:input];
        [self.session addOutput:output];
        //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
        output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
        //设置摄像机区域大小的设置:(这部分也可以自定义,显示自己想要的布局)
        AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
        layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        //设置为屏幕款高
        layer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        [self.view.layer insertSublayer:layer atIndex:99];
        //开始捕获图像:
        
        
        [_session startRunning];
    }
}
#pragma mark -> delegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count > 0) {
        SystemSoundID soundID = 1009;//1013;  1054
        //播放声音
        WeakSelf(weSelf, self);
        AudioServicesPlaySystemSound(soundID);
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        [self.session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //输出扫描字符串
        NSLog(@"%@",metadataObject.stringValue);
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"扫描成功" message:[NSString stringWithFormat:@"二维码内容:\n%@",metadataObject.stringValue] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [weSelf.session startRunning];
        }];
        [alertVC addAction:action];
        [self presentViewController:alertVC animated:YES completion:^{
        }];
        
        
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
